package com.syx.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.syx.entity.Goods;
import com.syx.entity.User;
import com.syx.service.GoodsService;
import com.syx.util.FileUploadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class GoodsController {
    @Resource
    private GoodsService service;

    @RequestMapping("login.do")
    public String login(User user, HttpSession session) {
       User users = service.login(user);
        if (users != null){
            session.setAttribute("user",users);
            return "redirect:list.do";
        }else{
            return  "redirect:index.jsp";
        }
    }

    @RequestMapping("list.do")
    public String list(Model model,
                       HttpSession session,
                       @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){
        PageHelper.startPage(pageNum,6);
        User user =(User) session.getAttribute("user");
        Integer uid = user.getUid();
        Integer sta = user.getSta();
        Map map = new HashMap();
        map.put("uid", uid);
        map.put("sta", sta);
        List list = service.list(map);
        PageInfo pageInfo = new PageInfo(list);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("map",map);
        return "list";
    }

    @RequestMapping("addTo.do")
    public String addTo(Model model,HttpSession session){
        return "add";
    }

    @RequestMapping("type.do")
    @ResponseBody
    public Object typeList(){
        List list = service.typeList();
        return list;
    }

    @RequestMapping("brand.do")
    @ResponseBody
    public Object brandList(){
        List list = service.brandList();
        return list;
    }


    @RequestMapping("add.do")
    @ResponseBody
    public Object add(Goods goods, HttpSession session, MultipartFile photo){
        System.out.println(goods.getPid());
        System.out.println(goods.getTid());
        if (photo.getSize()>0){
            String upload = FileUploadUtil.load(session, photo, "upload");
            goods.setPic(upload);
        }
        int list = service.add(goods);
        return list;
    }
}
